package Lono::Fetcher::Client::CookingLight;

use strict;
use warnings;

=head1 NAME
  
  Lono::Fetcher::Client::CookingLight - a recipe fetcher for cookinglight.com

=head1 SYNOPSIS

  my $response = Lono::Fetcher::Client::CookingLight::handle( $html );

=head1 DESCRIPTION

=cut

use base qw( Lono::Fetcher::Client::Base );

use Lono::Fetcher::Response;
use Lono::Recipe::Builder;

my %FIELDS = 
    ('name' => qr{<!--\sPAGE\sTITLE\s-->.*?
                  <span\sclass="item_header">([^<]+)</span>}ismx,

     'description' => qr{<!--\sSECTION\sDESCRIPTION\s-->.*? 
			             <span\sclass="item_body"><span\sclass="i">
                         (.*?)</span>}ismx,

     'preparation' => qr{<!--\sRECIPE\sINSTRUCTIONS\s-->.*?<br/>.*?
                         <span\sclass="item_body">(.*?)</span>}ismx, 

     'ingredients' => qr{<!--\sRECIPE\sINGREDIENTS\s-->.*?
                         <span\sclass="item_body"\sstyle="line-height:16px">
                         \s*(.*?)</span>}ismx,
    );

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub handle {
    my ( $self, $html ) = @_;

    my $response = Lono::Fetcher::Response->new;

    return $response;
}

sub _get_name {
    my ($self, $html) = @_;
    my $name = $self->_parse_with_regex($FIELDS{'name'}, $html);
    return $name;
}

sub _get_ingredients {
    my ($self, $html) = @_;

    # Try to field out the ingredients
    my $ingredients_blob = $self->_parse_with_regex($FIELDS{'ingredients'}, $html);

    # Remove any links
    # TODO: keep track of links so we can reference other recipes
    $ingredients_blob =~ s{</?a[^>]*>}{}msig;

    my @raw_ingredients = map { _fix_ingredient_line( $_ ) } 
                          grep length, split(m{\s*<(?:br|p)\s*/?>\s*}msi, 
                                             $ingredients_blob);

    return @raw_ingredients;
}

sub _fix_ingredient_line {
    my ( $html ) = shift;
    print $html, "\n";
    my ( $amount, $rest ) = ( $html =~ m{<core.+">(.*)&#160[^>]+(.*)\s*}ismx ) ? ( $1, $2 ) : ( '', '' );

    my $ingredient = '';
    if ( $amount ) {
        $ingredient = $amount . ' ' . $rest;
    } else {
        $ingredient = $rest;
    }

    return $ingredient;
}

sub _get_description {
    my ($self, $html) = @_;
    my $description = $self->_parse_with_regex($FIELDS{'description'}, $html);
    return $description;
}

sub _get_preparation {
    my ($self, $html) = @_;
    my $preparation = $self->_parse_with_regex($FIELDS{'preparation'}, $html);

    # Turn paragraph markers into newlines  
    $preparation =~ s{<p>}{\n\n}ismg;

    # Strip remaining HTML
    $preparation =~ s{</?[^>]+>}{}g;

    # Trim excess whitespace at beginning and end
    $preparation =~ s{^[\n\r\s]*}{}sm;
    $preparation =~ s{[\n\r\s]*$}{}s;
    
    # Get rid of extraneous newlines
    $preparation =~ s{[\n\r]{2,}}{\n\n}g;
    
    return $preparation;
}

1;
